<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="登记时间" prop="registerTime">
        <el-date-picker
          v-model="formData.registerTime"
          type="date"
          value-format="x"
          placeholder="选择登记时间"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="oid">
        <el-input v-model="formData.oid" placeholder="请输入订单号"/>
      </el-form-item>
      <el-form-item label="店铺" prop="shopId">
        <select-basic-shop v-model="formData.shopId" :shop-id-filter="shopIdFilter"/>
      </el-form-item>
      <el-form-item label="返款日期" prop="refundTime">
        <el-date-picker
          v-model="formData.refundTime"
          type="date"
          value-format="x"
          placeholder="选择返款日期"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio label="礼品单"/>
          <el-radio label="佣金单"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="返款金额" prop="refundMoney">
        <el-input-number v-model="formData.refundMoney" placeholder="自动计算（订单金额+佣金金额）"  :disabled="true" />
      </el-form-item>
      <el-form-item label="订单金额" prop="orderMoney">
        <el-input-number v-model="formData.orderMoney" placeholder="请输入订单金额"/>
      </el-form-item>
      <el-form-item label="佣金金额" :prop="formData.type === '佣金单' ? 'businessMoney' : ''">
        <el-input-number v-model="formData.businessMoney" placeholder="请输入佣金金额"/>
      </el-form-item>
      <el-form-item label="礼品成本" :prop="formData.type === '礼品单' ? 'giftCost' : ''"  >
        <el-input-number v-model="formData.giftCost" placeholder="请输入礼品成本"/>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {Business, BusinessApi} from '@/api/business/operation/business/order'
import {useUserStore} from "@/store/modules/user";

/** 业务-运营-补单 表单 */
defineOptions({name: 'BusinessForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  registerTime: undefined,
  shopId: undefined,
  refundTime: undefined,
  type: undefined,
  refundMoney: undefined,
  orderMoney: undefined,
  businessMoney: undefined,
  giftCost: undefined,
  oid: undefined,
  remark: undefined,
})
const formRules = reactive({
  registerTime: [{required: true, message: '登记时间不能为空', trigger: 'blur'}],
  shopId: [{required: true, message: '店铺不能为空', trigger: 'blur'}],
  type: [{required: true, message: '类型不能为空', trigger: 'change'}],
  orderMoney: [{required: true, message: '订单金额不能为空', trigger: 'blur'}],
  oid: [{required: true, message: '订单号不能为空', trigger: 'blur'}],
  businessMoney: [{required: true, message: '佣金金额不能为空', trigger: 'blur'}],
  giftCost: [{required: true, message: '礼品成本不能为空', trigger: 'blur'}],
  refundMoney: [{required: true, message: '返款不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

const shopIdFilter = ref('')
const userStore = useUserStore()
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)

  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BusinessApi.getBusiness(id)
    } finally {
      formLoading.value = false
    }
  }

  if (!formData.value.shopId) {
    const shopIds = userStore.user.shopIds
    shopIdFilter.value = userStore.user.shopIds
    // 先判断 shopIds 存在且不是空字符串，再进行分割
    if (shopIds && typeof shopIds === 'string' && shopIds.trim() !== '') {
      formData.value.shopId = shopIds.split(',')[0];
    }
  }

  if (!formData.value.registerTime) {
    formData.value.registerTime = new Date().getTime()
  }

}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Business
    if (formType.value === 'create') {
      await BusinessApi.createBusiness(data)
      message.success(t('common.createSuccess'))
    } else {
      await BusinessApi.updateBusiness(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    registerTime: undefined,
    shopId: undefined,
    refundTime: undefined,
    type: undefined,
    refundMoney: undefined,
    orderMoney: undefined,
    businessMoney: undefined,
    giftCost: undefined,
    oid: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}

watch(
  [() => formData.value.orderMoney, () => formData.value.businessMoney],
  ([order, business]) => {
    // 使用空值合并运算符处理undefined/null，转换为0参与计算
    formData.value.refundMoney = (order ?? 0) + (business ?? 0) || undefined;
  },
  { immediate: true }
);
</script>
